<template>
  <div class="wrap">
    <van-form>
      <van-field
        v-model="formData.age"
        name="年龄"
        label="年龄"
        placeholder="请填写年龄"
        :rules="rules"
      />
     <div class="btn-wrap" @click="onSubmit">
        <button class="btn">保存</button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, watch, computed } from 'vue'
import { showSuccessToast, showFailToast } from 'vant';
import { useRouter, useRoute } from 'vue-router'
import { postData } from '@/request/request.js'
let router = useRouter()
let route = useRoute()
let query = route.query
// localStorage.setItem('user_id', query.user_id)
// localStorage.setItem('access_token', query.access_token)
// localStorage.setItem('open_id', query.open_id)
// localStorage.setItem('currentPath', query.currentPath)

const formData = reactive({
  age: 0,
})

const rules = ref([{ required: true, message: '请填写年龄' }])

let init = () => {
  postData('/user/info/get', {})
    .then((res) => {
      formData.age = res?.datas?.age
    })
    .catch((err) => {
      console.log(err)
    })
}

let onSubmit = (values) => {
  let user_id = localStorage.getItem('user_id')
  if (!user_id) {
    Toast.fail('请先绑定手机号')
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/loginPhone/loginPhone',
      })
    }, 2000)
  } else {
    postData('/user/info/update', { age: formData.age })
      .then((res) => {
        showSuccessToast('保存成功');
        init()
      })
      .catch((err) => {
         showFailToast('保存失败');
      })
  }

  // this.$refs.form.validate((valid) => {
  //   if (valid) {
  //     console.log('表单验证成功');
  //     // 表单验证成功后执行的操作，例如提交数据等。
  //   } else {
  //     console.log('表单验证失败');
  //     // 表单验证失败后的处理逻辑。
  //   }
  // });
}

onMounted(() => {
  init()
})
</script>

<style scoped>
.btn-wrap {
  width: 100%;
  height: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 0.3rem;
}

.btn-wrap .btn {
  border: none;
  width: 90%;
  height: 0.35rem;
  line-height: 0.35rem;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #d5ad57;
  border-radius: 0.35rem;
  color: #fff;
  font-weight: 400;
  font-size: 0.16rem;
}
</style>
